<template>
  <div class="ship-info-container">
    <div style="position: relative">
      <div class="content">
        <el-tabs type="border-card" class="eltabs">
          <el-tab-pane label="详细信息">
            <div class="flex-column">
              <div class="flex-row" style="justify-content: space-between">
                <div class="content-txt1">
                  {{
                    info?.chineseName ||
                    shipInfo?.localName ||
                    info?.name ||
                    shipInfo?.shipNameEn ||
                    info?.mmsi ||
                    shipInfo?.mmsi ||
                    '未知船舶'
                  }}
                </div>
                <div @click="handToParentClose()">
                  <el-icon class="close-icon" style="color: #409eff; cursor: pointer; font-size: 22px;"><Close /></el-icon>
                </div>
              </div>
              <div class="line"></div>
              <div style="display:flex;flex-direction:column;">
                <div class="text">
                  <div>英文船名:</div>
                  <div>{{ info?.englishName || shipInfo?.shipNameEn || info?.name || "" }}</div>
                </div>
                <div class="textBox">
                  <div class="text">
                    <div>MMSI:</div>
                    <div>{{ info?.mmsi || shipInfo?.mmsi || "" }}</div>
                  </div>

                  <div class="text">
                    <div>船长:</div>
                    <div>{{ shipInfo?.loa || "" }}</div>
                  </div>
                  <div class="text">
                    <div>船宽:</div>
                    <div>{{ shipInfo?.bm || "" }}</div>
                  </div>
                  <div class="text">
                    <div>经度:</div>
                    <div>{{ info?.lat ? info.lat.toFixed(6) : "" }}</div>
                  </div>
                  <div class="text">
                    <div>纬度:</div>
                    <div>{{ info?.lon ? info.lon.toFixed(6) : "" }}</div>
                  </div>
                  <div class="text">
                    <div>航速:</div>
                    <div>{{ parseInt(info?.sog) + '节' || "" }}</div>
                  </div>
                  <div class="text">
                    <div>呼号:</div>
                    <div>{{ shipInfo?.callsign || "" }}</div>
                  </div>
                  <div class="text">
                    <div>航向:</div>
                    <div>{{ info?.cog || "" }}</div>
                  </div>
                  <div class="text">
                    <div>IMO:</div>
                    <div>{{ shipInfo?.imo || "" }}</div>
                  </div>
                  <div class="text">
                    <div>类型:</div>
                    <div>
                      {{
                        setShipType(info?.shipType) ||
                        setShipType(shipInfo?.shipTypeCode) ||
                        ""
                      }}
                    </div>
                  </div>
                  <div class="text">
                    <div>预抵港:</div>
                    <div>{{ info?.destination || "" }}</div>
                  </div>
                  <div class="text">
                    <div>预抵时间:</div>
                    <div>{{ info?.eta ? new Date(info.eta * 1000).toLocaleString() : "" }}</div>
                  </div>
                  <div class="text">
                    <div>吃水:</div>
                    <div>{{ parseInt(info?.draught) || "" }}</div>
                  </div>
                  <div class="text">
                    <div>船籍:</div>
                    <div><img :src="setFlag(info?.region)" style="width:24px;height:14px;" /></div>
                  </div>
                  <div class="text">
                    <div>更新时间:</div>
                    <div>{{ info?.time ? new Date(info.time * 1000).toLocaleString() : "" }}</div>
                  </div>
                </div>
                <div class="text">
                  <div>状态:</div>
                  <div v-if="info?.status !== undefined">
                    {{ getStatus(info.status) }}
                  </div>
                </div>
                <div class="text">
                  <div>联系方式:</div>
                  <div>{{ shipInfo?.contactNo || "" }}</div>
                </div>
                <div class="text">
                  <div>船舶航迹:</div>
                  <div style="width: 300px; margin-left: 10px">
                    <el-slider :step="20" show-stops :marks="marks" v-model="historyTime" @change="changeSlider">
                    </el-slider>
                  </div>
                </div>
              </div>

              <div class="line"></div>
              <div class="func">
                <div @click="addWhiteList">白名单</div>
                <div @click="seePath">航迹</div>
                <div @click="setCenter">居中</div>
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="船舶档案">
            <div class="flex-column">
              <div class="flex-row" style="justify-content: space-between">
                <div class="content-txt1">
                  {{
                    info?.chineseName ||
                    shipInfo?.localName ||
                    info?.name ||
                    shipInfo?.shipNameEn ||
                    info?.mmsi ||
                    shipInfo?.mmsi ||
                    '未知船舶'
                  }}
                </div>
                <div @click="handToParentClose()">
                  <el-icon class="close-icon" style="color: #409eff; font-size: 22px;"><Close /></el-icon>
                </div>
              </div>
              <div class="line"></div>
              <div class="text">
                <div>中文船名:</div>
                <div>{{ info?.chineseName || shipInfo?.localName || "" }}</div>
              </div>
              <div class="text">
                <div>英文船名:</div>
                <div>{{ info?.englishName || shipInfo?.shipNameEn || info?.name || "" }}</div>
              </div>
              <div class="text">
                <div>造船厂:</div>
                <div>{{ shipInfo?.shipyard || "" }}</div>
              </div>
              <div class="text">
                <div style="width: 120px">造船厂（英文）:</div>
                <div></div>
              </div>
              <div class="text">
                <div style="width: 120px">船舶所有人:</div>
                <div></div>
              </div>
              <div class="text">
                <div style="width: 120px">建成日期:</div>
                <div>{{ shipInfo?.buildDate || "" }}</div>
              </div>
              <div class="textBox">
                <div class="text">
                  <div>国籍:</div>
                  <div>{{ info?.region }}</div>
                </div>
                <div class="text">
                  <div>船籍港:</div>
                  <div>{{ shipInfo?.registrationPort || "" }}</div>
                </div>
                <div class="text">
                  <div>MMSI:</div>
                  <div>{{ info?.mmsi || shipInfo?.mmsi || "" }}</div>
                </div>
                <div class="text">
                  <div>船舶类型:</div>
                  <div>
                    {{
                      setShipType(info?.shipType) ||
                      setShipType(shipInfo?.shipTypeCode) ||
                      ""
                    }}
                  </div>
                </div>
                <div class="text">
                  <div>IMO:</div>
                  <div>{{ shipInfo?.imo || "" }}</div>
                </div>
                <div class="text">
                  <div>呼号:</div>
                  <div>{{ shipInfo?.callsign || "" }}</div>
                </div>
                <div class="text">
                  <div>船长:</div>
                  <div>{{ shipInfo?.loa || "" }}</div>
                </div>
                <div class="text">
                  <div>船宽:</div>
                  <div>{{ shipInfo?.bm || "" }}</div>
                </div>
                <div class="text">
                  <div>型深:</div>
                  <div>{{ shipInfo?.depth || "" }}</div>
                </div>

                <div class="text">
                  <div>型宽:</div>
                  <div>{{ shipInfo?.lbp || "" }}</div>
                </div>
                <div class="text">
                  <div>总吨:</div>
                  <div>{{ shipInfo?.gross || "" }}</div>
                </div>
                <div class="text">
                  <div>净吨:</div>
                  <div>{{ shipInfo?.net || "" }}</div>
                </div>
                <div class="text">
                  <div>最小干舷:</div>
                  <div>{{ shipInfo?.minFreeboard || "" }}</div>
                </div>
              </div>
              <div class="line"></div>
              <div class="func">
                <div>白名单</div>
                <div @click="seePath">航迹</div>
                <div @click="setCenter">居中</div>
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="实时报警">
            <div class="flex-column">
              <div class="flex-row" style="justify-content: space-between">
                <div class="content-txt1">
                  {{
                    info?.chineseName ||
                    shipInfo?.localName ||
                    info?.name ||
                    shipInfo?.shipNameEn ||
                    info?.mmsi ||
                    shipInfo?.mmsi ||
                    '未知船舶'
                  }}
                </div>
                <div @click="handToParentClose()">
                  <el-icon class="close-icon" style="color: #409eff; font-size: 22px;"><Close /></el-icon>
                </div>
              </div>
              <div class="line"></div>
              <div class="list">
                <div class="list_item" v-for="(item, index) in warnList" :key="index">
                  <div class="list_item_content">
                    <div class="list_item_info">报警名称</div>
                    <div class="list_item_info">
                      报警规则 <span>{{ item.eventContent }}</span>
                    </div>
                    <div class="list_item_info">
                      报警时间 <span>{{ item.warningTime }}</span>
                    </div>
                    <div class="list_item_info">处理状态 <span>未处理</span></div>
                    <div class="list_item_info">
                      报警区域 <span>{{ item.address }}</span>
                    </div>
                  </div>
                  <div class="list_item_option">
                    <div>
                      <el-icon><Setting /></el-icon>
                      规则详情
                    </div>
                    <div>
                      <el-icon><Mouse /></el-icon>
                      结束
                    </div>
                    <div @click="locate(item)">
                      <el-icon><Pointer /></el-icon>
                      报警位置
                    </div>
                    <div @click="setCenternew(item)">
                      <el-icon><FullScreen /></el-icon>报警区域
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
      <el-dialog
        title="白名单"
        v-model="dialogVisibleLast"
        :modal="false"
        custom-class="customDialog"
        width="500px"
      >
        <el-form ref="formLastRef" :model="formLast" :rules="rulesLst" label-width="130px">
          <el-form-item label="船舶MMSI" prop="mmsi">
            <el-input type="text" maxlength="50" placeholder="请输入船舶MMSI" v-model="formLast.mmsi">
              <template #append>
                <el-button :icon="Search" @click="remoteMethod"></el-button>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="船名" prop="shipName">
            <el-input type="text" maxlength="100" placeholder="请输入船名" v-model="formLast.shipName"></el-input>
          </el-form-item>
          <el-form-item label="船只类型" prop="type">
            <el-radio-group v-model="formLast.type">
              <el-radio :label="1">自有船只</el-radio>
              <el-radio :label="2">工作船只</el-radio>
              <el-radio :label="0">其他</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="白名单生效时间" prop="startTime">
            <el-date-picker 
              v-model="formLast.startTime" 
              align="right" 
              type="datetime" 
              placeholder="选择日期"
              popper-class="elDatePicker" 
              style="width: 100%;" 
              value-format="YYYY/MM/DD HH:mm:ss"
              :disabled-date="disabledDate"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="白名单失效时间" prop="endTime">
            <el-date-picker 
              v-model="formLast.endTime" 
              align="right" 
              type="datetime" 
              placeholder="选择日期"
              popper-class="elDatePicker" 
              style="width: 100%;" 
              value-format="YYYY/MM/DD HH:mm:ss"
              :disabled-date="disabledDate"
            ></el-date-picker>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button type="primary" size="small" @click="submit">保 存</el-button>
            <el-button size="small" @click="dialogVisibleLast = false">取 消</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, watch, onBeforeUnmount, nextTick, defineProps, defineEmits } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Close, Setting, Mouse, Pointer, Search, FullScreen } from '@element-plus/icons-vue'
import { shipHistory, shipDetails } from "@/api/map/map"
import { addWhiteList as addWhiteListApi, getWhiteListDetail, detailByMMSI, editWhiteList } from "@/api/shipGrouping"
import { useRouter } from 'vue-router'

// 导入国旗图片
import flagCN from '@/assets/images/CN.png'
import flagDK from '@/assets/images/DK.png'
import flagCY from '@/assets/images/CY.png'
import flagLR from '@/assets/images/LR.png'
import flagMT from '@/assets/images/MT.png'
import flagPA from '@/assets/images/PA.png'
import flagKR from '@/assets/images/KR.png'
import flagSG from '@/assets/images/SG.png'
import flagLU from '@/assets/images/LU.png'
import flagMH from '@/assets/images/MH.png'
import jingzhunIcon from '@/assets/images/jingzhun.png'

// 全局声明天地图对象
declare const window: Window & {
  T: any
}
const T = window.T

// 定义接口
interface ShipInfoData {
  id?: number
  localName?: string
  shipNameEn?: string
  mmsi?: string
  loa?: string
  bm?: string
  callsign?: string
  imo?: string
  shipTypeCode?: number
  contactNo?: string
  buildDate?: string
  registrationPort?: string
  depth?: string
  lbp?: string
  gross?: string
  net?: string
  minFreeboard?: string
  shipyard?: string
  [key: string]: any
}

interface FormLastData {
  id: number | null
  shipName: string | null
  mmsi: string | null
  type: number | null
  startTime: string | null
  endTime: string | null
}

// 定义组件的 Props 类型
interface Props {
  info: {
    mmsi?: string;
    chineseName?: string;
    name?: string;
    lon?: number;
    lat?: number;
    [key: string]: any;
  };
  shipInfo: {
    mmsi?: string;
    localName?: string;
    shipNameEn?: string;
    [key: string]: any;
  };
  map: any;
}

const props = defineProps<Props>();

// 定义 Emits 类型
type Emits = {
  (event: 'closeShip'): void;
  (event: 'center', num: any): void;
  (event: 'closeTabData'): void;
}

const emit = defineEmits<Emits>();

const router = useRouter()

const activeName = ref('first')
const isShow = ref(true)
const marks = {
  0: '2h',
  20: '4h',
  40: '8h',
  60: '12h',
  80: '24h',
  100: '48h'
}
const historyTime = ref(0)
const ship = ref(null)
const nowLng = ref(null)
const nowlat = ref(null)
const schedule = ref(0)
const lines = ref([])
const labels = ref([])
const tlines = ref([])
const list = ref([])
const dataVal = ref(null)
const shipInfoData = ref<ShipInfoData>({})
const warnList = ref([])
const dialogVisibleLast = ref(false)
const formLast = ref<FormLastData>({
  id: null,
  shipName: null,
  mmsi: null,
  type: null,
  startTime: null,
  endTime: null
})
const rulesLst = {
  shipName: [
    { required: true, message: '请输入船名', trigger: 'blur' }
  ],
  mmsi: [
    { required: true, message: '请输入船舶MMSI', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择船只类型', trigger: 'blur' }
  ],
  startTime: [
    { required: true, message: '请选择白名单生效时间', trigger: 'blur' }
  ],
  endTime: [
    { required: true, message: '请选择白名单失效时间', trigger: 'blur' }
  ],
}
const pickerOptions = {
  disabledDate(time) {
    return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
  },
}

const setShipType = (val) => {
  let result
  if (
    val == 60 ||
    val == 61 ||
    val == 62 ||
    val == 63 ||
    val == 64 ||
    val == 65 ||
    val == 66 ||
    val == 67 ||
    val == 68 ||
    val == 69
  ) {
    result = "客船"
  } else if (
    val == 70 ||
    val == 71 ||
    val == 72 ||
    val == 73 ||
    val == 74
  ) {
    result = "货船"
  } else if (val == 33) {
    result = "作业船"
  } else if (val == 52) {
    result = "拖船"
  } else if (val == 30) {
    result = "渔船"
  } else {
    result = "其他"
  }

  return result
}

const getStatus = (val: number | undefined): string => {
  if (typeof val === 'number') {
    if (val === 8 || val === 0) {
      return "航行"
    } else if (val === 5 || val === 1) {
      return "停泊"
    }
  }
  return "未知"
}

const rest = () => {
  formLast.value = {
    id: null,
    shipName: null,
    mmsi: null,
    type: null,
    startTime: null,
    endTime: null,
  }
  nextTick(() => {
    formLastRef.value.resetFields()
  })
}

const remoteMethod = () => {
  if (formLast.value.mmsi !== '') {
    var data = {
      mmsi: formLast.value.mmsi,
    }
    detailByMMSI(data).then((response) => {
      if (response.data) {
        formLast.value.shipName = response.data.localName ? response.data.localName : response.data.shipNameEn
      } else {
        ElMessage.warning("未查询到该船舶信息")
      }
    })
  } else {
    ElMessage.warning("请输入船舶MMSI")
  }
}

const submit = () => {
  formLastRef.value.validate(valid => {
    if (new Date(formLast.value.startTime) > new Date(formLast.value.endTime)) {
      ElMessage.warning("生效时间不能大于失效时间")
      return
    }
    if (valid) {
      var data = {
        id: formLast.value.id,
        shipName: formLast.value.shipName,
        mmsi: formLast.value.mmsi,
        type: formLast.value.type,
        startTime: formLast.value.startTime,
        endTime: formLast.value.endTime,
      }
      if (formLast.value.id) {
        editWhiteList(data).then(response => {
          ElMessage.success("操作成功")
          dialogVisibleLast.value = false
        })
      } else {
        addWhiteListApi(data).then(response => {
          ElMessage.success("操作成功")
          dialogVisibleLast.value = false
        })
      }
    }
  })
}

const addWhiteList = () => {
  rest()
  dialogVisibleLast.value = true
  getWhiteListDetail(props.info.mmsi || props.shipInfo.mmsi).then(response => {
    if (response.data) {
      formLast.value = response.data
    } else {
      formLast.value.mmsi = props.info.mmsi || props.shipInfo.mmsi
      formLast.value.shipName = props.info.chineseName || props.shipInfo.localName || props.info.name || props.shipInfo.shipNameEn || ''
    }
  })
}

const handToParentClose = () => {
  cleanMap()
  emit('closeShip')
}

const getShip = (val: ShipItem) => {
  if (marker.value && marker.value.parentNode) {
    let parent = marker.value.parentNode;
    parent.removeChild(marker.value);
  }

  let lng = val.lon;
  let lat = val.lat;
  window.map.panTo(new T.LngLat(lng, lat));

  let img = document.createElement("img");
  // 使用导入的图片资源
  img.src = jingzhunIcon;
  let latlng = new T.LngLat(lng, lat);
  marker.value = document.createElement("div");
  img.style.width = "25px";
  img.style.height = "25px";
  img.style.transform = `rotate(${val.cog}deg)`;
  marker.value.appendChild(img);
  marker.value.style.position = "absolute";
  window.map.getPanes().overlayPane.appendChild(marker.value);
  let pos = window.map.lngLatToLayerPoint(latlng);
  marker.value.style.top = pos.y - 10 + "px";
  marker.value.style.left = pos.x - 10 + "px";
  marker.value.style.zIndex = "1000";
};

const getshipDetails = (mmsi: string) => {
  shipDetails(mmsi).then((res) => {
    if (res.code === 200 && res.data) {
      shipInfoData.value = res.data
    } else {
      shipInfoData.value = {}
    }
  })
}

const setCenter = () => {
  if (props.map && props.info) {
    props.map.panTo(new T.LngLat(props.info.lon, props.info.lat))
  }
}

const seePath = () => {
  if (props.info?.mmsi) {
    const routeUrl = router.resolve({
      path: '/flightPath',
      query: {
        count: props.info.mmsi,
      },
    })
    window.open(routeUrl.href, '_blank')
  }
}

const getShipHistory = (id) => {
  let hours = null
  switch (historyTime.value) {
    case 0:
      hours = 2
      break
    case 20:
      hours = 4
      break
    case 40:
      hours = 8
      break
    case 60:
      hours = 12
      break
    case 80:
      hours = 24
      break
    case 100:
      hours = 48
      break
  }
  let obj = {
    hours: parseInt(hours),
    shipId: id,
  }
  shipHistory(obj).then((res) => {
    if (res.code == 200) {
      schedule.value = 0
      list.value = []
      let data = res.data
      for (let i = 0; i < data.length; i++) {
        for (let j = 0; j < data[i].length; j++) {
          let val = JSON.parse(data[i][j])
          if (j > 0 && (val.lon - JSON.parse(data[i][j - 1]).lon > 0.1)) {
            console.log('异常-----', val)
            continue
          }
          list.value.push(val)
        }
      }

      dataVal.value =
        parseInt(list.value.length / (hours * 20)) > 1
          ? parseInt(list.value.length / (hours * 20))
          : 1
      schedule.value += 1
    }
  })
}

const cleanMap = () => {
  lines.value.forEach((ele) => {
    props.map.removeOverLay(ele)
  })
  labels.value.forEach((ele) => {
    props.map.removeOverLay(ele)
  })
  tlines.value.forEach((ele) => {
    props.map.removeOverLay(ele)
  })
}

const setLocusPlayData = (scheduleIndex: number) => {
  if (list.value && list.value.length === 0) {
    return
  }
  
  nowLng.value = list.value[scheduleIndex].lon
  nowlat.value = list.value[scheduleIndex].lat // 保留一下当前marker坐标
  
  let latlng = new T.LngLat(
    list.value[scheduleIndex].lon,
    list.value[scheduleIndex].lat
  )
  
  // 当前坐标和上一个坐标比较，没有变化或者变化不大不新增label标志
  if (scheduleIndex != 0) {
    let preLat = list.value[scheduleIndex - 1].lat.toFixed(2)
    let preLng = list.value[scheduleIndex - 1].lon.toFixed(2)
    
    if (
      preLat == list.value[scheduleIndex].lat.toFixed(2) &&
      preLng == list.value[scheduleIndex].lon.toFixed(2)
    ) {
      let origin = new T.LngLat(
        list.value[scheduleIndex - 1].lon,
        list.value[scheduleIndex - 1].lat
      )
      let terminalPoint = new T.LngLat(
        list.value[scheduleIndex].lon,
        list.value[scheduleIndex].lat
      )
      let points = [origin, terminalPoint]
      let line = new T.Polyline(points, {
        color: "red",
        weight: 2,
        opacity: 0.5,
      })
      props.map.addOverLay(line)
      lines.value.push(line)
    } else {
      // 从第二个点位开始，轨迹连线
      let origin = new T.LngLat(
        list.value[scheduleIndex - 1].lon,
        list.value[scheduleIndex - 1].lat
      )
      let terminalPoint = new T.LngLat(
        list.value[scheduleIndex].lon,
        list.value[scheduleIndex].lat
      )
      let points = [origin, terminalPoint]
      let line = new T.Polyline(points, {
        color: "red",
        weight: 2,
        opacity: 0.5,
      })
      props.map.addOverLay(line)
      lines.value.push(line)
      
      // 设置时间标志
      let lng, lat
      if (scheduleIndex % 2 == 0) {
        lng = (list.value[scheduleIndex].lon + list.value[scheduleIndex].lon * 0.99995) / 2
        lat = (list.value[scheduleIndex].lat + list.value[scheduleIndex].lat * 1.00007) / 2
      } else {
        lng = (list.value[scheduleIndex].lon + list.value[scheduleIndex].lon * 1.00005) / 2
        lat = (list.value[scheduleIndex].lat + list.value[scheduleIndex].lat * 0.99995) / 2
      }

      let label = new T.Label({
        text: new Date(list.value[scheduleIndex].time * 1000).toLocaleString(),
        position: new T.LngLat(lng, lat),
      })
      label.setOpacity(0.7)
      label.setBackgroundColor("rgba(255,255,255,0.3)")

      // 创建地图文本对象
      props.map.addOverLay(label)
      labels.value.push(label)

      // label连线
      let termPoint = label.getLngLat()
      let Tpoints = [latlng, termPoint]
      let tline = new T.Polyline(Tpoints, {
        color: "#333333",
        weight: 2,
      })

      // 点是基于label的左上角，根据情况设置label偏移对应左上角/右下角
      if (scheduleIndex % 2 == 0) {
        label.setOffset(new T.Point(-120, -10))
      } else {
        label.setOffset(new T.Point(-15, 10))
      }
      props.map.addOverLay(tline)
      tlines.value.push(tline)
    }
  } else {
    // 设置时间标志
    let lng = (list.value[scheduleIndex].lon + list.value[scheduleIndex].lon * 0.99995) / 2
    let lat = (list.value[scheduleIndex].lat + list.value[scheduleIndex].lat * 1.00007) / 2

    let label = new T.Label({
      text: new Date(list.value[scheduleIndex].time * 1000).toLocaleString(),
      position: new T.LngLat(lng, lat),
    })
    label.setOpacity(0.7)
    label.setBackgroundColor("rgba(255,255,255,0.3)")

    // 创建地图文本对象
    props.map.addOverLay(label)
    labels.value.push(label)

    // label连线
    let termPoint = label.getLngLat()
    let Tpoints = [latlng, termPoint]
    let tline = new T.Polyline(Tpoints, {
      color: "#333333",
      weight: 2,
    })

    // 点是基于label的左上角，根据情况设置label偏移对应左上角/右下角
    if (scheduleIndex % 2 == 0) {
      label.setOffset(new T.Point(-120, -10))
    } else {
      label.setOffset(new T.Point(-15, 10))
    }
    props.map.addOverLay(tline)
    tlines.value.push(tline)
  }
}

const changeSlider = (): void => {
  cleanMap()
  schedule.value = 0
  if (props.info?.mmsi) {
    getShipHistory(props.info.mmsi)
  }
}

const getWarning = (mmsi: string) => {
  // 匹配本船的实时预警 在index页调用
  let str = localStorage.getItem("warnList")

  if (str) {
    let obj = JSON.parse(str)
    warnList.value = obj.filter((item: any) => {
      return item.mmsi == mmsi
    })
  }
}

const marker = ref<any>(null)

const locate = (val: any): void => {
  if (marker.value) {
    props.map.removeOverLay(marker.value)
  }
  props.map.panTo(new window.T.LngLat(val.lon, val.lat))
  
  let icon = new window.T.Icon({
    iconUrl: "http://api.tianditu.gov.cn/img/map/marker.png",
    iconSize: new window.T.Point(19, 27),
    iconAnchor: new window.T.Point(10, 25),
  })
  
  marker.value = new window.T.Marker(new window.T.LngLat(val.lon, val.lat), {
    icon: icon,
  })
  props.map.addOverLay(marker.value)

  emit("closeTabData")
  setTimeout(() => {
    props.map.removeOverLay(marker.value)
  }, 10000)
}

const setCenternew = (val: any) => {
  if (!val || !val.lon || !val.lat || !window.map) {
    console.warn('Invalid parameters for setCenternew:', val);
    return;
  }

  try {
    const lng = typeof val.lon === 'string' ? parseFloat(val.lon) : val.lon;
    const lat = typeof val.lat === 'string' ? parseFloat(val.lat) : val.lat;
    
    if (isNaN(lng) || isNaN(lat)) {
      console.warn('Invalid coordinates in setCenternew:', lng, lat);
      return;
    }
    
    // 安全地访问map对象
    if (window.map && window.map.panTo && window.T) {
      window.map.panTo(new window.T.LngLat(lng, lat));
    }
  } catch (error) {
    console.error('Error in setCenternew:', error);
  }
}

const formLastRef = ref<FormInstance>()

// 修改国旗设置方法
const setFlag = (val: string): string => {
  if (!val) return "";
  
  let url = ""
  if (val === "CN" || val === "TW" || val === "HK") {
    url = flagCN;
  } else if (val === "DK") {
    url = flagDK;
  } else if (val === "CY") {
    url = flagCY;
  } else if (val === "LR") {
    url = flagLR;
  } else if (val === "MT") {
    url = flagMT;
  } else if (val === "PA") {
    url = flagPA;
  } else if (val === "KR") {
    url = flagKR;
  } else if (val === "SG") {
    url = flagSG;
  } else if (val === "LU") {
    url = flagLU;
  } else if (val === "MH") {
    url = flagMH;
  }
  return url;
}

const disabledDate = (time: Date): boolean => {
  return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
}

// 监听schedule变化
watch(() => schedule.value, (val) => {
  setLocusPlayData(schedule.value - 1)
  if (schedule.value < list.value.length) {
    schedule.value += 1
  }
})

onBeforeUnmount(() => {
  cleanMap()
})
</script>

<style scoped lang="less">
.content {
  /* width: 350px; */
  height: 100%;
  /* background: rgba(0, 0, 0, 0.5); */
  position: fixed;
  left: 0;
  top: 60px;
  z-index: 1000;
  display: flex;
  flex-direction: row;
}

.eltabs {
  height: 100%;
  width: 380px;
}

.flex-column {
  display: flex;
  flex-direction: column;
}

.flex-row {
  width: 100%;
  display: flex;
  flex-direction: row;
  align-items: center;
}

.content-txt1 {
  font-size: 16px;
  color: #409eff;
}

.el-icon-circle-close {
  font-size: 22px;
}

.line {
  width: 100%;
  height: 1px;
  margin: 10px auto;
  background: #d5d5d5;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 12px;
  padding-right: 8px;
  color: #4386c6;
}

.custom-tree-node-label {
  display: block;
  width: 125px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.shipNum {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.collItem:hover {
  cursor: pointer;
}

.collItem {
  color: #409eff;
}

.textBox {
  display: flex;
  flex-wrap: wrap;
  justify-items: flex-start;
}

.text {
  display: flex;
  flex-direction: row;
  align-items: center;
  color: #06acef;
  font-size: 14px;
  white-space: nowrap;
  margin-bottom: 15px;
}

.text>div:first-child {
  width: 65px;
  color: #c6c9cd;
}

.text>div:last-child {
  width: 120px;
}

.func {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  color: #06acef;
  font-size: 14px;
}

.func>div {
  margin-left: 20px;
}

.func>div:hover {
  cursor: pointer;
}

.list {
  height: 750px;
  overflow: auto;

  .list_item {
    padding: 10px;
    border-bottom: 1px solid #06acef;
    font-size: 14px;

    .list_item_content {
      display: flex;
      align-items: center;
      justify-content: flex-start;
      flex-wrap: wrap;

      .list_item_info {
        width: 50%;

        margin-bottom: 12px;

        span {
          color: rgb(188, 195, 255);
        }
      }
    }

    .list_item_option {
      display: flex;
      align-items: center;
      justify-content: flex-end;
      margin-top: 10px;
      color: #409eff;

      div {
        margin-left: 10px;
      }

      div:hover {
        cursor: pointer;
      }
    }
  }
}

::-webkit-scrollbar {
  width: 4px;
  height: 10px;
  background-color: #f5f5f5;
}

/*定义滚动条轨道 内阴影+圆角*/
::-webkit-scrollbar-track {
  -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
  border-radius: 10px;
  background-color: #f5f5f5;
}

/*定义滑块 内阴影+圆角*/
::-webkit-scrollbar-thumb {
  border-radius: 10px;
  -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
  background-color: #4376ec;
}

::v-deep .el-dialog.customDialog {
  margin-top: 20vh !important;
  background: #3c4167 !important;
}

::v-deep .el-form-item__label {
  color: #fff;
}

::v-deep .el-input-group__append {
  background: rgba(29, 32, 52, 0.9);
  border-color: rgb(94, 102, 160);
  color: #fff;
}

::v-deep .el-radio__label {
  color: #fff;
}
</style>

<style scoped src="@/assets/datePark.css"></style>